package com.daocao.hua.http;

import android.content.Context;

import com.daocao.hua.api.Api;
import com.daocao.hua.util.RBInfo;
import com.daocao.hua.util.RBLog;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by MasterDong on 16/8/4.
 */
public class HttpUtil {

    private Context mContext;


    private HttpUtil(Context context) {
        mContext = context;
    }

    public static HttpUtil getInstance(Context context) {
        return new HttpUtil(context);
    }

    public List<String> doGet(String strUrl, Map<String, String> requestProperties) {
        return this.doGet(strUrl, requestProperties, 30000L, 20000L);
    }

    /**
     * http头部信息
     *
     * @return
     */
    public Map<String, String> getDefaultRequestProperties() {
        HashMap requestProperties = new HashMap();
        requestProperties.put("Content-Type", "application/json");
        requestProperties.put("accept", "*/*");
        requestProperties.put("connection", "Keep-Alive");
        requestProperties.put("RABITOKEN", RBInfo.getInstance().getToken());
//        requestProperties.put("RABIAPPVERSION", PackageUtil.getVersionName(mContext));
        return requestProperties;
    }

    public List<String> doGet(String strUrl, Map<String, String> requestProperties, long connectTimeout, long readTimeout) {
        ArrayList contents = new ArrayList();
        URL url = null;
        HttpURLConnection httpConnection = null;
        BufferedReader reader = null;

        try {
            url = new URL(strUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setConnectTimeout((int) connectTimeout);
            httpConnection.setReadTimeout((int) readTimeout);
            Set e;
            if (requestProperties != null) {
                e = requestProperties.keySet();
                Iterator parameter = e.iterator();

                while (parameter.hasNext()) {
                    String i = (String) parameter.next();
                    httpConnection.setRequestProperty(i, (String) requestProperties.get(i));
                }
            }
            httpConnection.connect();
            reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

            String s;
            while ((s = reader.readLine()) != null) {
                contents.add(s);
            }

            reader.close();
        } catch (Exception var23) {
            RBLog.e("error occured when executing dotGet(), msg:", var23.getMessage());
        } finally {
            if (httpConnection != null) {
                try {
                    httpConnection.disconnect();
                } catch (Exception var22) {
                    ;
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception var21) {
                    ;
                }
            }

        }

        return contents;
    }

    public String dotGetAndDownload(String strUrl, String savePath, String fileName) {
        String strfile = savePath.endsWith(File.separator) ? savePath + fileName : savePath + File.separator + fileName;
        URL url = null;
        HttpURLConnection httpConnection = null;
        RandomAccessFile targetFile = null;

        try {
            int e = 0;
            int contentLength = 0;
            boolean currRead = false;
            url = new URL(strUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestProperty("User-Agent", "Internet Explorer");
            String sProperty = "bytes=" + e + "-";
            httpConnection.setRequestProperty("RANGE", sProperty);
            int in = 1;

            while (true) {
                String header = httpConnection.getHeaderFieldKey(in);
                if (header != null) {
                    if (!header.equals("Content-Length")) {
                        ++in;
                        continue;
                    }

                    contentLength = Integer.parseInt(httpConnection.getHeaderField(header));
                }

                InputStream var31 = httpConnection.getInputStream();
                targetFile = new RandomAccessFile(strfile, "rw");

                int var30;
                for (byte[] buff = new byte[1024]; (var30 = var31.read(buff, 0, 1024)) > 0 && e < contentLength; e += var30) {
                    targetFile.write(buff, 0, var30);
                }

                String var16 = strfile;
                return var16;
            }
        } catch (Exception var28) {
            RBLog.e("error occured when executing dotGetAndDownload(), msg:", var28.getMessage());
        } finally {
            if (httpConnection != null) {
                try {
                    httpConnection.disconnect();
                } catch (Exception var27) {
                    ;
                }
            }

            if (targetFile != null) {
                try {
                    targetFile.close();
                } catch (Exception var26) {
                    ;
                }
            }

        }

        return null;
    }

    public List<String> doPost(String strUrl, Map<String, String> requestProperties, Map<String, String> requestParameters) {
        return this.doPost(strUrl, requestProperties, requestParameters, 30000L, 20000L);
    }

    public List<String> doPost(String strUrl, Map<String, String> requestProperties, Map<String, String> requestParameters, long connectTimeout, long readTimeout) {
        ArrayList contents = new ArrayList();
        URL url = null;
        HttpURLConnection httpConnection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;

        try {
            url = new URL(strUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            httpConnection.setRequestMethod("POST");
            httpConnection.setConnectTimeout((int) connectTimeout);
            httpConnection.setReadTimeout((int) readTimeout);
            httpConnection.setUseCaches(false);
            httpConnection.setInstanceFollowRedirects(true);

            Set e;
            if (requestProperties != null) {
                e = requestProperties.keySet();
                Iterator parameter = e.iterator();

                while (parameter.hasNext()) {
                    String i = (String) parameter.next();
                    httpConnection.setRequestProperty(i, (String) requestProperties.get(i));
                }
            }

            httpConnection.connect();

            out = new DataOutputStream(httpConnection.getOutputStream());
            if (requestParameters != null) {
                e = requestParameters.keySet();
                int var37 = 0;

                String var36;
//                for (Iterator var16 = e.iterator(); var16.hasNext(); out.writeBytes(var36 + "=" + (String) requestParameters.get(var36))) {
//                    var36 = (String) var16.next();
//                    if (var37++ > 0) {
//                        out.writeBytes("&");
//                    }
//                }
                for (Iterator var16 = e.iterator(); var16.hasNext(); out.writeBytes(var36 + "" + (String) requestParameters.get(var36))) {
                    var36 = (String) var16.next();
                    if (var37++ > 0) {
                        out.writeBytes("&");
                    }
                }

                out.flush();
            }

            reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

            String var35;
            while ((var35 = reader.readLine()) != null) {
                contents.add(var35);
            }
        } catch (Exception var33) {
            RBLog.e("error occured when executing dotPost(), msg:", var33.getMessage());
        } finally {
            if (httpConnection != null) {
                try {
                    httpConnection.disconnect();
                } catch (Exception var32) {
                    ;
                }
            }

            if (out != null) {
                try {
                    out.close();
                } catch (Exception var31) {
                    ;
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception var30) {
                    ;
                }
            }

        }

        return contents;
    }

    public List<String> doPostAndUpload(String strUrl, Map<String, String> requestProperties, Map<String, String> requestParameters, Map<String, File> uploadFiles) {
        ArrayList contents = new ArrayList();
        URL url = null;
        HttpURLConnection httpConnection = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        Object fileInputStream = null;

        try {
            url = new URL(strUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(true);
            httpConnection.setUseCaches(false);
            httpConnection.setInstanceFollowRedirects(true);
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Connection", "Keep-Alive");
            Set e;
            String twoHyphens;
            if (requestProperties != null) {
                e = requestProperties.keySet();
                Iterator boundary = e.iterator();

                while (boundary.hasNext()) {
                    twoHyphens = (String) boundary.next();
                    httpConnection.setRequestProperty(twoHyphens, (String) requestProperties.get(twoHyphens));
                }
            }

            httpConnection.connect();
            out = new DataOutputStream(httpConnection.getOutputStream());
            String var67;
            if (requestParameters != null) {
                e = requestParameters.keySet();
                int var65 = 0;

                for (Iterator fieldNames = e.iterator(); fieldNames.hasNext(); out.writeBytes(var67 + "=" + (String) requestParameters.get(var67))) {
                    var67 = (String) fieldNames.next();
                    if (var65++ > 0) {
                        out.writeBytes("&");
                    }
                }

                out.flush();
            }

            String var66;
            if (uploadFiles != null) {
                var66 = "/r/n";
                twoHyphens = "--";
                var67 = "*****";
                Set var68 = uploadFiles.keySet();
                Iterator var16 = var68.iterator();

                label462:
                while (true) {
                    while (true) {
                        if (!var16.hasNext()) {
                            break label462;
                        }

                        String fieldName = (String) var16.next();
                        File uploadFile = (File) uploadFiles.get(fieldName);
                        if (!uploadFile.exists()) {
                            RBLog.e("", "\'" + uploadFile + "\' does not exists");
                        } else {
                            String fileName = uploadFile.getName();
                            out.writeBytes(twoHyphens + var67 + var66);
                            out.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"" + var66);
                            out.writeBytes(var66);
                            FileInputStream fIn = null;

                            try {
                                fIn = new FileInputStream(uploadFile);
                                byte[] e1 = new byte[1024];
                                boolean len = true;

                                int var69;
                                while ((var69 = fIn.read(e1)) != -1) {
                                    out.write(e1, 0, var69);
                                }

                                out.writeBytes(var66);
                                out.flush();
                            } catch (Exception var61) {
                                RBLog.e("error occured when uploading \'" + fileName + "\', msg:", var61.getMessage());
                            } finally {
                                if (fIn != null) {
                                    try {
                                        fIn.close();
                                    } catch (Exception var60) {
                                        ;
                                    }
                                }

                            }
                        }
                    }
                }
            }

            reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

            while ((var66 = reader.readLine()) != null) {
                contents.add(var66);
            }
        } catch (Exception var63) {
            RBLog.e("error occured when executing doPostAndUpload(), msg:", var63.getMessage());
        } finally {
            if (httpConnection != null) {
                try {
                    httpConnection.disconnect();
                } catch (Exception var59) {
                    ;
                }
            }

            if (out != null) {
                try {
                    out.close();
                } catch (Exception var58) {
                    ;
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception var57) {
                    ;
                }
            }

            if (fileInputStream != null) {
                try {
                    ((FileInputStream) fileInputStream).close();
                } catch (Exception var56) {
                    ;
                }
            }

        }

        return contents;
    }

    public static void get(String url,Callback callback){
        Request request = new Request.Builder().url(url).build();
        Api.okhttpClient.newCall(request).enqueue(callback);
    }

    public static void post(String url, String json, Callback callback){
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Api.okhttpClient.newCall(request).enqueue(callback);
    }
}
